/**
 * Copyright By Nanjing Fujitsu Nanda Software Technology Co., Ltd
 * 下午3:49:48
 * LoginUrlEntryPoint.java
 * 
 */
package com.fujitsu.nanjing.tieba.security;

import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.fujitsu.nanjing.tieba.ibator.CoreUser;
import com.fujitsu.nanjing.tieba.service.UserService;

/**
 * @author Administrator
 * 
 */
@Component
public class LoginUrlEntryPoint implements AuthenticationEntryPoint {
	private final String LASTACCESS = "lastAccess";
	private final String LOGIN = "login";
	protected final String CURRENTUSER = "currentUser";
	protected final String USERID = "userId";
	private static final String LoginPath = "/login";
	@Resource
	private UserService userService;
	@Override
	public void commence(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException authException)
			throws IOException, ServletException {
		String targetUrl = null;

		String url = request.getRequestURI();
		// 取得登陆前的url
		String refererUrl = request.getHeader("Referer");
		// TODO 增加处理逻辑
		UserDetails userDetails = null;

		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		if (auth == null) {
			response.sendRedirect("/login");
			return;
		}
		userDetails = (UserDetails) auth.getPrincipal();
		CoreUser user = userService.findById(userDetails.getUsername());
		HttpSession session = request.getSession();
		session.setAttribute(LOGIN, "true");
		session.setAttribute(CURRENTUSER, user.getNickname());
		session.setAttribute(USERID, user.getUserid());
		session.setAttribute(LASTACCESS, user.getLastvisited());
		user.setLastvisited(new Date());
		userService.update(user);
		String[] args = url.split("//");
		String rootUrl = args[0] + args[1].split("/")[0];
		if (refererUrl.startsWith(rootUrl)
				&& !refererUrl.startsWith(rootUrl + LoginPath)) {
			targetUrl = refererUrl;
		} else {
			targetUrl = rootUrl;
		}
		response.sendRedirect(targetUrl);
	}

}
